import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
declare var BMap: any;
declare var BMapLib: any;
declare var echarts: any;
declare var toMapPoint: any;
declare var changeTime: any;
declare var window: any;
declare var clearCanvasLayerEnd: any;
declare var BMAP_ANCHOR_BOTTOM_RIGHT:any;
@Component({
	selector: 'sa-car-info',
	templateUrl: './car-info.component.html',
	styleUrls: ['./gpsTrack.css']
})
export class CarInfoComponent implements OnInit {
	constructor(private jsonApiService: JsonApiService, private router: Router) {};
	fuzzyArr: any = []; //当搜索车牌,编号时模糊查询出的结果.
	startTime: string = '';
	endTime: string = '';
	carNumber: string = '';
	deviceId: string = '';
	companyName: string = '';
	allCarCompany: any = [];
	selectedCompany: string = '';
	mp: any; //百度地图
	mapSize: any = 10;
	myTrackLine: any;
	trackCanvasLayer: any; //轨迹图层
	moveCanvasLayer: any; //轨迹移动添加点图层

	markerClustererObj: any; //聚能合marker对象
	clickedCarMarker: any; //点击查看过的车辆
	areaPly: any; //用于记录地区范围
	searhValue: string = ''; //检索地区时的搜索值
	fuzzyVal: string = ''; //查询车牌号跟deviceId时的搜索值
	searhType: string = '1'; //搜索类型(1:地区,2:车牌,3:decevid)
	opts = {
		width: 259
	}; //信息框的大小
	weightUnit: string = ' 吨'; //车辆信息的重量单位
	carTreeHeight:number;//树形图高度
	//表格部分参数
//	isTable: boolean = false; //是否展开表格
//	tableData: any = []; //table数据
//	resultTableData: any = []; //前端分页table数据
//	activeSelected: string = '';//row选择的数据
//	totalCount: number = 0; //分页总条数
//	curPage: number = 1; //分页当前页
//	fixPageSize: number = 5; //扩展的pagesize控制
//	searchKey: string = ''; //搜索keyword
	allCarArr: any = []; //后台过来的所有车辆的数据
//	nullloadArr: any = []; //空载车辆
//	heftloadArr: any = []; //重载
//	travelArr: any = []; //行驶
//	staticArr: any = []; //静止
//	offlineArr: any = []; //离线车辆
//	tableHeight: any = 208; //表格高度
	//路线追踪及数据更新参数
	uplodTimer: any; //定时更新数据定时器
	lineStyle = {
		star: false,
		end: true,
		color: true,
		infoUrl: ''
	}; //追踪路线样式
	fristMarker: any; //追踪时的第一个坐标标注
	polylinetimer: any; //追踪轨迹定时器
	TrackLineArr: any = []; //追踪轨迹数据数组
	endMarker: any; //追踪轨迹数时的最后一个点
	traceRouteType: boolean = false; //判断是否处于追踪状态中
	isStopStatus: boolean = false; //是否在追踪时候暂停

	treeStatus: string = '收起'; //树形图展开或者收起状态
	btnDownTime: number = 0; //截留btn点击展开频率

	weightChart: any; //重量折线图
	speedChart: any; //速度折线图
	lineColor: string = 'rgba(87, 147, 243, 0.8)';
	echartOption: any; //折线图基础配置 	
	speedOption: any; //速度表基础配置 	
	speedChartTimer: any; //速度定时器
	weightChartTimer: any; //重量定时器
	frequency: number = 10000; //更新的频率,单位毫秒
	isSpeedChart: boolean = true; //打开关闭速度图
	myGeoAddress: any; //实例化坐标转换地址对象

	mapInfoWindow: any;

	carTreeData = []; //车辆树形图数据
	slectedCarId = ''; //车辆树形图选中的车辆ID
	notOnlineCar = false;
	
	findCarCount=0;//车辆树搜出的总数
	findCarIndex=0;//车辆树当前定位
	findString='';//搜索提示
	
	
	tolocaltrack: boolean = false;//是否有权限跳轨迹页面
	toloadDatas: boolean = false;//是否有权限跳数据下载页面
	getCartreeMess(carMess){
		this.slectedCarEvent(carMess);
	}
	//树形图单击选中辆车,打开对应地图信息窗体
	slectedCarEvent(param) {
		this.deviceId = param.deviceId;
		this.carNumber = param.carNumber;
		this.operateMarker(param);
	}
	//打开信息窗口
	operateMarker(obj) {
		let that = this;
		if(that.traceRouteType) {
			that.jsonApiService.message('请关闭正在追踪的车辆')
			return;
		}
		that.clickedCarMarker = obj;
		this.getWeightUnit(obj.deviceId).then((carInfoData)=>{
			that.createContent(carInfoData, false).then((content) => {
				$('.traceRoute').click(function() {
					that.traceRoute(obj.deviceId)
				});
				$('.toCarTrack').click(function() {
					that.toCarTrackHtml();
				})
				$('.toDataload').click(function() {
					that.toloadDataHtml();
				})
				$('.closeInfo').click(function() {
					if(that.traceRouteType) {
						that.closeInfo()
					} else {
						that.mp.closeInfoWindow()
					}
	
				});
			});
		})
	}
	//根据设备Id获取实时数据
	getWeightUnit(decevid) {
		var that = this;
		return new Promise(function(resolve, reject) {
			let params = 'deviceId=' + decevid;
			that.jsonApiService.http("realtime/getRealTimeDataForBase.html", params).subscribe(resDate => {
				if(resDate.data.unit == '2') {
					that.weightUnit = ' kg';
				}
				if(resDate.data.unit == '1'){
					that.weightUnit = ' 吨';
				}
			});
			
			let reqdata = 'deviceId=' + decevid;
			that.jsonApiService.http("realtime/getRealTimeData.html", reqdata).subscribe(result => {
				if(result.data.unit == '2') {
					that.weightUnit = ' kg';
				} 
				if(result.data.unit == '1'){
					that.weightUnit = ' 吨';
				}
				resolve(result.data)
			})
		})
	}
	//搜索类型变更事件
	changeType() {
		this.searhValue = '';
		this.fuzzyVal = '';
		this.fuzzyArr = [];
	}

	//点击选中的车牌号或设备id确认fuzzyVal值
	getFuzzyVal(val) {
		this.fuzzyVal = val;
		this.fuzzyArr = [];
	}

	//当搜索车牌或设备编号的模糊查询
	fuzzySearch() {
		var searchValue = common.stringTrim(this.fuzzyVal);
		if(searchValue == '') {
			this.fuzzyArr = [];
			return;
		}
		var searchArr = this.allCarArr
		var result = [];
		var len = searchArr.length;
		if(this.searhType == '2') {
			for(var i = 0; i < len; i++) {
				let carNum = searchArr[i].carNumber;
				if(carNum) {
					if(searchArr[i].carNumber.match(searchValue)) {
						result.push(searchArr[i].carNumber);
					}
				}
			}
		}
		if(this.searhType == '3') {
			for(var i = 0; i < len; i++) {
				let deviceId = searchArr[i].deviceId;
				if(deviceId) {
					if(searchArr[i].deviceId.match(searchValue)) {
						result.push(searchArr[i].deviceId);
					}
				}
			}
		}
		this.fuzzyArr = result;
	}

	//通过坐标获取到实际地址
	getStringAddress(point) {
		return new Promise(function(resolve, reject) {
			var address = '';
			this.myGeoAddress.getLocation(point, function(result) {
				if(result) {
					address = result.address;
					resolve(address);
				}
			})
		}.bind(this))
	}
	//判断是否有权限
	btnData:any = []; // 权限按钮
    lnglatLossPermission = false;
	initBtn() {
	    this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_car:realTime')));
			if(this.btnData) {
					for(let item of this.btnData) {
							if(item.sourceKey === "lnglat:loss:view" && item.parentId) {
									this.lnglatLossPermission = true;
									break
							}
					}
				}
        let routerStr = localStorage.getItem('s-menu');
        if(!routerStr) return;
        let findTrack = false;
        let findload = false;
        let routerObj = JSON.parse(decodeURIComponent(routerStr));
        for (let item of routerObj){
            for(let iems of item.children){
                if(iems.sourceKey === 'track:localtrack'){//车辆轨迹菜单权限
                   findTrack = true;
                }
                if(iems.sourceKey === 'data-manage:loadDat'){//数据下载菜单权限
                   findload = true;
               }
            }
           if(findload&&findload) break;
        }
       this.tolocaltrack = findTrack;
       this.toloadDatas = findload;
	}
	ngOnInit() {
	    this.initBtn();//权限按钮
		let deviceHeight = window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;
		$('#baiduMap').height(deviceHeight-145);
		this.carTreeHeight = deviceHeight - 240;
		let that = this;
		let map = new BMap.Map('baiduMap',{enableMapClick: false}); //创建地图实例
		map.centerAndZoom(new BMap.Point(117.7953288, 28.2862345), 5); //初始化地图，设置中心点坐标和地图级别
		map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
		map.addControl(new BMap.NavigationControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,offset: new BMap.Size(12, 68)}));//地图缩放控件
		map.addEventListener("zoomend", function() {that.mapSize = this.getZoom()});
		this.mp = map;
		this.myGeoAddress = new BMap.Geocoder();//坐标转换成实际地址
		this.initCarInfo();
//		this.uplodCarInfo();
		this.retrieverRegion();
		$('.mapMonitor .btn').click(function() {$('.selectListType').removeClass('selectListType');$(this).addClass('selectListType')})
		$('.diy_seachInp').bind('input propertychange', function() {that.fuzzySearch()});
		this.addEventWindowResize();
		this.mapInfoWindow = new BMap.InfoWindow('', this.opts); // 创建信息窗口对象 
	}
	//resize监听,动态设置树形图宽度
	addEventWindowResize() {
		$(window).on('resize', function() {
			var wrapWidth = $("#wrap").width();
			var divTreeWidth = $(".divTree").width();
			$('.treeRight').width(wrapWidth - divTreeWidth - 12 + 'px');
		})
	}
	//drag,动态设置树形图宽度
	draggingEvent() {
		var clickX;
		var warp = $("#wrap");
		var treeElement = $(".divTree");
		var treeRight = $(".treeRight");
		var min = 300;
		var max = 0;
		var leftOffset = warp.offset().left;
		$(document).on('mousemove', function(e) {
			var wrapWidth = warp.width();
			max = wrapWidth / 2;
			var divTreeWidth = treeElement.width();
			var treeRightWidth = treeRight.width();
			clickX = e.pageX;
			if(clickX - leftOffset > min) {
				if(clickX - leftOffset < max) {
					treeElement.width(clickX - leftOffset + 'px');
					treeRight.width(wrapWidth - clickX + leftOffset - 12 + 'px');
				} else {
					treeElement.width(max + 'px');
					treeRight.width(wrapWidth - max - 12 + 'px');
				}
			} else {
				treeElement.width(min + 'px');
				treeRight.width(wrapWidth - min - 12 + 'px');
			}
		});
		$(document).mouseup(function(e) {
			e.cancelBubble = true;
			$(document).unbind('mousemove')
		})
	}
	//地区检索
	retrieverRegion() {
		//建立检索匹配对象
		let that = this;
		let ac = new BMap.Autocomplete({"input": "suggestId","location": that.mp});
		ac.addEventListener("onhighlight", function(e) { //鼠标放在下拉列表上的事件
			var str = "";
			var _value = e.fromitem.value;
			var value = "";
			if(e.fromitem.index > -1) {
				value = _value.province + _value.city + _value.district + _value.street + _value.business;
			}
			str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
			value = "";
			if(e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province + _value.city + _value.district + _value.street + _value.business;
			}
			str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			// G("searchResultPanel").innerHTML = str;
		});
		ac.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件和点击 
			that.getBoundary();
		});
		$("#suggestId").bind("keydown", function(e) {
			var theEvent = e || window.event;
			var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
			if(code == 13) {
				that.getBoundary();
			}
		});
	}
	//离开页面,关闭所有定时器
	ngOnDestroy() {
		window.clearInterval(this.uplodTimer);
		window.clearInterval(this.polylinetimer);
		window.clearInterval(this.speedChartTimer);
		window.clearInterval(this.weightChartTimer);
		$(document).unbind('keyup'); //移除键盘回车事件
		$(window).unbind('resize');
	}
   
	//初始化地图视图,加载数据,并分类处理
	lossLngLatData:any = [];
	initCarInfo() {
		this.jsonApiService.http2("gps/getcarGpsInfoList.html", null).subscribe(result => {
			let len = result.length;
			this.allCarArr = [];
			this.lossLngLatData = [];
			// 有权限情况,可查看丢失的经纬度数据的车辆信息
			if(this.lnglatLossPermission){
			    for(var i = 0; i < len; i++) {
                    var changePoint = toMapPoint(result[i]);
                    if(changePoint) {
                        this.allCarArr.push(result[i]);
                        if(this.clickedCarMarker) {
                            if(this.clickedCarMarker.deviceId == result[i].deviceId) {
                                this.clickedCarMarker = result[i];

                            }
                        }
                    }else{
                        //显示丢失的经纬度数据,模拟生成随机坐标,围绕0-0.05之间
                        result[i].lng = Math.random() * 0.05;
                        result[i].lat = Math.random() * 0.05;
                        this.allCarArr.push(result[i]);
                        this.lossLngLatData.push(result[i])
                    }
                }
			}else{
			    // 没有权限则过滤掉异常数据
			    for(var i = 0; i < len; i++) {
                    var x = parseInt(result[i].x);
                    var y = parseInt(result[i].y);
                    if(x > 0 && y > 0) {
                        var changePoint = toMapPoint(result[i]);
                        if(changePoint) {
                            this.allCarArr.push(result[i]);
                            if(this.clickedCarMarker) {
                                if(this.clickedCarMarker.deviceId == result[i].deviceId) {
                                    this.clickedCarMarker = result[i];
    
                                }
                            }
                        }
                    }
                }
			}
			this.MarkerClusterer(this.allCarArr);
		})
	}
	//生成聚能和marker标注
	MarkerClusterer(data) {
		let markers = [];
		for(let i = 0; i < data.length; i++) {
			let obj = data[i];
			if(obj.lng && obj.lat) {//使用转换过百度坐标的坐标位置
				let marker = new BMap.Marker(new BMap.Point(obj.lng, obj.lat), {
					icon: new BMap.Icon("assets/img/trackImage/car01.png", new BMap.Size(25, 25))
				}); // 创建marker点
				let that = this;
				marker.addEventListener("click", function(e) {
					that.deviceId = obj.deviceId;
					that.operateMarker(obj);
				})
				markers.push(marker)
			}
		}
		this.markerClustererObj = new BMapLib.MarkerClusterer(this.mp, {
			markers: markers
		});
	}
	//关闭信息框,初始化地图视图
	closeInfo() {
		this.isStopStatus = false;
		this.clickedCarMarker = false;
		this.initializeMapView();
		this.mp.closeInfoWindow();
		this.initCarInfo();
		this.traceRouteType = false;
		if(this.uplodTimer) {
			window.clearInterval(this.uplodTimer)
		}
//		this.uplodCarInfo();
		clearCanvasLayerEnd(this.mp);

	}

	//更新定时器
	uplodCarInfo() {
		var that = this;
		this.uplodTimer = setInterval(function() {
			this.markerClustererObj.clearMarkers();
			this.initCarInfo(); //重新加载MarkerClusterer
		}.bind(this), that.frequency);
	}

	//点击列表,定位车辆
//	tableItemPoint(data) {
//		this.deviceId = data.deviceId;
//		this.activeSelected = data.id;
//		this.operateMarker(data);
//	}

	//通过车辆的deviceId找到对应车辆数据并返回
	findCar(deviceId) {
		let result;
		let data = this.allCarArr;
		let len = data.length;
		for(let i = 0; i < len; i++) {
			let id = data[i].deviceId;
			if(id == deviceId) {
				result = data[i];
			}
		}
		return result;
	}

	//	创建自定义信息框 @param data 信息框显示的数据信息（obj）  @param stopRouteBtn  监听是否追踪状态 return  elment（html元素）	
	createContent(obj, stopRouteBtn) {
		var that = this;
		var routeOrStop;
		if(!obj.speed) {obj.speed = '0'}
		for(let item in obj){
			obj[item] = obj[item]||'--';
		}
		if(stopRouteBtn) {
			routeOrStop = '<li  class="stopRoute lis" name="stop" ><button class="qxbtn">暂停</button></li>';
		} else {
			routeOrStop = '<li  class="traceRoute lis" ><button class="qxbtn">实时追踪</button></li>';
		}
		return new Promise((resolve, reject) => {
			this.myGeoAddress.getLocation(new BMap.Point(obj.x, obj.y), function(result) {
				let localtrackType='';
				let loadDataType='';
				if(!this.tolocaltrack) localtrackType='disabled';
				if(!this.toloadDatas) loadDataType='disabled';
				
				if(result) {
					//警报类型切换，1，是司机断电		2，设备关机
					let alarmType = '';
					if(obj.alarmType == '1'){
						alarmType = '断电警报';
					}
					if(obj.alarmType == '2'){
						alarmType = '离线警报';
					}
					else{
						alarmType = '--';
					}
					// 在线离线判断
					let lineState = '';
					if(obj.runStatus=='0'){
						lineState = '<span style="color:#333333;position:absolute;right:50px;background-color:#ffffff;height:34px;">[离线]</span>';
					}else{
						lineState = '<span style="color:#2bb56b;position:absolute;right:50px;background-color:#ffffff;height:34px;">[在线]</span>';
					}
					
					
					var address = result.address;
//					var elment = '<div class="massageDiv infoBox">' +
//						'<p class="p1" style="text-align: center">' + obj.carNumber + ' [ ID ' + obj.deviceId + ']</span><span class="closeInfo"> × </span></p>' +
//						'<div class="content">' +
//						'<div class="contentText">' +
//						'<ul>' +
//						'<li><span class="leftSpan">定位技术：</span><span class="rightSpan"> 北斗+GPS </span></li>' +
//						'<li><span class="leftSpan">公司名称：</span><span class="rightSpan"> ' + obj.companyName + '</span></li>' +
//						'<li><span class="leftSpan">当前重量：</span><span class="rightSpan"> ' + common.twoDecimal(obj.weight) + this.weightUnit + '</span></li>' +
//						'<li><span class="leftSpan">当前速度：</span><span class="rightSpan"> ' + obj.speed + 'km/h</span></li>' +
//						'<li><span class="leftSpan">经纬度值：</span><span class="rightSpan"> ' + obj.x + ' , ' + obj.y + '</span></li>' +
//						'<li><span class="leftSpan">更新时间：</span><span class="rightSpan"> ' + obj.carUploadDate + '</span></li>' +
//						'<li><span class="leftSpan">当前位置：</span><span class="rightSpan"> ' + address + '</span></li>' +
//						'</ul></div></div>' +
//						'<div class="navList"><ul>' + '<li class="device_id" hidden>' + obj.deviceId + '</li>' +
//						'<li class="car_number" hidden>'+obj.carNumber+'</li>' +
//						'<li class="infoMenu"><button class="qxbtn toCarTrack '+localtrackType+'" '+localtrackType+'>车辆轨迹</button></li>'+
//						'<li class="infoMenu"><button class="qxbtn toDataload '+loadDataType+'" '+loadDataType+'>数据下载</button></li>'+
//						routeOrStop +
//						'</ul></div>' +
//						'</div>';
						
					var elment = 
						'<div class="massageDiv BMap-info">' +
							'<p class="title"><img class="position-img" src="assets/img/bmap/position.png" />' + address + ' [北斗+GPS]</span>'+ lineState +
							'<span class="closeInfo"> × </span></p>' +
							'<div class="content">' +
								'<div class="contentText">' +
									'<ul class="row">' +
										'<li class="col-sm-4 module no-padding"><span class="li-lable">车牌号码</span><span class="li-value">'+obj.carNumber+'['+obj.deviceId+']</span></li>'+
										'<li class="col-sm-4 module no-padding"><span class="li-lable">公司名称</span><span class="li-value" style="white-space: nowrap;text-overflow: ellipsis;overflow: hidden;" title='+obj.companyName+'>'+obj.companyName+'</span></li>'+
										'<li class="col-sm-4 module no-padding"><span class="li-lable">定位时间</span><span class="li-value">'+obj.carUploadDate+'</span></li>'+
										'<li class="col-sm-4 module no-padding"><span class="li-lable">当前重量</span><span class="li-value">'+common.twoDecimal(obj.weight) + this.weightUnit+'</span></li>'+
										'<li class="col-sm-4 module no-padding"><span class="li-lable">报警类型</span><span class="li-value">'+alarmType+'</span></li>'+
										'<li class="col-sm-4 module no-padding"><span class="li-lable">报警时间</span><span class="li-value">'+obj.alarmTime+'</span></li>'+
										'<li class="col-sm-4 module no-padding"><span class="li-lable">当前车速[km/h]</span><span class="li-value">'+obj.speed+'</span></li>'+
										'<li class="col-sm-4 module no-padding"><span class="li-lable">电压[v]</span><span class="li-value">'+obj.voltage+'</span></li>'+
										'<li class="col-sm-4 module no-padding"><span class="li-lable">电压采集时间</span><span class="li-value">'+obj.voltageTime+'</span></li>'+
									'</ul>'+
								'</div>'+
							'</div>' +
							'<div class="navList">'+
								'<ul>' +
									'<li class="device_id" hidden>' + obj.deviceId + '</li>' +
									'<li class="car_number" hidden>'+obj.carNumber+'</li>' +
									routeOrStop +
									'<li class="lis"><button title="跳转车辆轨迹" class="toCarTrack qxbtn '+localtrackType+'" '+localtrackType+'><img src="assets/img/bmap/jump.png"/> 车辆轨迹</button></li>'+
									'<li class="lis"><button title="跳转数据下载" class="toDataload qxbtn '+loadDataType+'" '+loadDataType+'><img src="assets/img/bmap/jump.png"/> 数据下载</button></li>' +
								'</ul>'+
							'</div>' +
						'</div>';
				}
				var toMapP = toMapPoint(obj);
				// 经纬度丢失情况
				if(!toMapP){
				    this.jsonApiService.message('该车定位失败');
				    if(!this.lnglatLossPermission){
				        return;
				    }
				    var lossLngLat:any = {
				        lng:'0.0',
				        lat:'0.0'
				    }
				    for(let item of this.lossLngLatData){
				        if(item.deviceId == obj.deviceId){
				            lossLngLat.lng = item.lng;
				            lossLngLat.lat = item.lat;
				        }
				    }
				}
				var infoWindow = new BMap.InfoWindow(elment, {width : 508});  // 创建信息窗口对象 
				that.mp.openInfoWindow(infoWindow,new BMap.Point(toMapP.lng||lossLngLat.lng,toMapP.lat||lossLngLat.lat)); //开启信息窗口
				setTimeout(function() {
					if($('.pointer').length<1){
						$('.BMap_bottom').append('<div class="pointer"></div>');
					}
				}, 50);
				resolve(elment);
			}.bind(this))
			
		})
	}

	//地区搜索
	getBoundary() {
		let type = parseInt(this.searhType);
		let value = this.searhValue;

		if(type !== 1) {
			value = this.fuzzyVal;
		}
		let that = this;
		if(value == '') {
			return;
		}
		that.mp.closeInfoWindow();
		if(type == 1) {
			var bdary = new BMap.Boundary();
			bdary.get(value, function(rs) { //获取行政区域
				that.mp.removeOverlay(that.areaPly); //清除地图覆盖物       
				var count = rs.boundaries.length; //行政区域的点有多少个
				if(count < 1) {
					return;
				}
				that.areaPly = new BMap.Polygon(rs.boundaries[0], {
					strokeColor:'blue',
					fillColor:'red',
					strokeWeight:1,
					strokeOpacity:0.2,
					fillOpacity:0.2
				}); //建立多边形覆盖物
				that.mp.addOverlay(that.areaPly); //添加覆盖物
				that.mp.setViewport(that.areaPly.getPath()); //调整视野  
			});
		} else {
			that.clickedCarMarker = false;
			let datas = that.allCarArr;
			for(let i = 0; i < datas.length; i++) {
				let contrastVal;
				if(type == 2) {
					contrastVal = datas[i].carNumber;
				} else if(type == 3) {
					contrastVal = datas[i].deviceId;
				}
				if(contrastVal == value) {
					let obj = datas[i];
					that.clickedCarMarker = datas[i];
					this.getWeightUnit(obj.deviceId).then((carInfoData)=>{
						that.createContent(carInfoData, false).then((content) => {
							$('.closeInfo').click(function() {
								that.closeInfo();
							})
							$('.toCarTrack').click(function() {
								that.toCarTrackHtml();
							})
							$('.toDataload').click(function() {
								that.toloadDataHtml();
							})
							$('.traceRoute').click(function() {
								that.traceRoute(obj.deviceId);
							})
						});
					})
					break;
				}
			}
		}
	}

	//打开或关闭列表
//	openList() {
//		if(this.isTable) {
//			this.isTable = false;
//			$('#baiduMap').height(765);
//		} else {
//			this.isTable = true;
//			this.changeMapHeight(this.tableData.length);
//		}
//	}

	//表格部分 star 表格搜索
//	table_search() {
//		this.tableData = this.allCarArr;
//		if(this.searchKey == '' || !this.searchKey) {
//			this.totalCount = this.allCarArr.length;
//			this.client_pages(0, this.fixPageSize);
//			return;
//		}
//		var result = [];
//		for(var i = 0; i < this.tableData.length; i++) {
//			let val = this.tableData[i].deviceId;
//			let val2 = this.tableData[i].carNumber;
//			if(val.match(common.stringTrim(this.searchKey))) {
//				result.push(this.tableData[i]);
//			}
//			if(!val2) {
//				continue;
//			}
//			if(val2.match(common.stringTrim(this.searchKey))) {
//				result.push(this.tableData[i]);
//			}
//		}
//		this.changeMapHeight(result.length)
//		this.tableData = result;
//		this.totalCount = result.length;
//		this.curPage = 1;
//		this.client_pages(0, this.fixPageSize);
//	}
//	changeMapHeight(len) {
//		let mapObj = $('#baiduMap');
//		if(len == 0) {
//			this.tableHeight = 206;
//			mapObj.height(766 - this.tableHeight);
//			return;
//		} else {
//			if(len >= 5) {
//				len = 5;
//			}
//			this.tableHeight = 145 + 43 * len;
//		}
//		mapObj.height(766 - this.tableHeight);
//
//	}
	//  初始化加载list数据
//	load() {
//		let type = $('.selectListType').attr('name');
//		if(type && type !== 'allCar') {
//			if(this.isTable) {
//				this.loadTypelist(type);
//			}
//		} else {
//			this.tableData = this.allCarArr;
//			this.totalCount = this.allCarArr.length;
//			this.client_pages(0, this.fixPageSize);
//		}
//		if(this.searchKey !== '') {
//			this.table_search();
//		}
//
//	}
//	client_pages(start, length) {
//		var len = start + Number(length);
//		this.resultTableData = this.tableData.slice(start, len);
//	}
//	refresh() {
//		this.load();
//	}
	//分页回调
//	paginate(e) {
//		this.curPage = e.page + 1;
//		this.client_pages(e.first, e.rows);
//	}
	//分页pageSize回调事件
//	updatePageSize(e) {
//		this.curPage = 1;
//		this.fixPageSize = parseInt(e);
//		this.client_pages(0, this.fixPageSize);
//	}

	//根据类型加载表单
//	loadTypelist(type) {
//		this.curPage = 1;
//		this.isTable = true;
//		switch(type) {
//			case 'allCar':
//				this.tableData = this.allCarArr;
//				break;
//			case 'nullload':
//				this.tableData = this.nullloadArr;
//				break;
//			case 'heftload':
//				this.tableData = this.heftloadArr;
//				break;
//			case 'travel':
//				this.tableData = this.travelArr;
//				break;
//			case 'static':
//				this.tableData = this.staticArr;
//				break;
//			case 'offline':
//				this.tableData = this.offlineArr;
//				break;
//
//		}
//
//		let len = this.tableData.length
//		this.totalCount = len;
//		this.client_pages(0, this.fixPageSize);
//
//		this.changeMapHeight(len)
//
//	}
	/**初始化地图视图*/
	initializeMapView() {
		clearInterval(this.polylinetimer); //清除追踪定时器
		this.TrackLineArr = []; //清空路线数据对象
		clearTrackLine(this.mp); //清除地图轨迹路线
	}

	//轨迹追踪获取第一次坐标位置
	traceRoute(deviceId) {
		if(!deviceId) {
			return;
		}
		this.deviceId = deviceId;
		let reqdata = 'deviceId='+deviceId;
		this.jsonApiService.http("track/follow.html", reqdata).subscribe(result => {
			if(result.success) {
				this.mp.clearOverlays(); // 移除地图上的所有标注点	
				clearInterval(this.polylinetimer); //清除原有定时器
				this.TrackLineArr = []; //清空路线数据对象
				clearTrackLine(this.mp); //清除地图轨迹路线
				window.clearInterval(this.uplodTimer); //停止更新的定时器
				this.markerClustererObj.clearMarkers(); //清除更新定时器

				this.traceRouteType = true; //当前状态追踪
				let that = this;
				let obj = this.findCar(this.deviceId);
				var toMap = toMapPoint(result.data);
				if(!obj) {
					return;
				}
				for(let item in toMap) {
					obj[item] = toMap[item];
				}
				obj.carUploadDate = toMap.uploadDate;
				this.TrackLineArr.push(toMap); //添加到路线数组中
				let point = new BMap.Point(obj.lng, obj.lat);
				let carIcon = new BMap.Icon("assets/img/trackImage/car01.png", new BMap.Size(25, 25));
				this.fristMarker = new BMap.Marker(point, {icon: carIcon}); // 创建标注
				this.mp.addOverlay(this.fristMarker); //增加点
				this.getWeightUnit(deviceId).then((carInfoData)=>{
					that.createContent(carInfoData, false).then((content) => {
						$('.closeInfo').click(function() {
							that.closeInfo();
						})
						that.mapInfoWindow.disableCloseOnClick();
						setTimeout(function() {
							that.runTimer(obj.deviceId)
						}, that.frequency)
					});
				})
			} else {
				this.jsonApiService.message(result.message);
			}
		})
	}

	//轨迹追踪时的定时器行为
	runTimer(deviceId) {
		let that = this;
		setTimeout(function() {
			that.mp.removeOverlay(that.fristMarker); //删除第一个点
		}, that.frequency - 100)
		that.polylinetimer = setInterval(function() {
			let reqdata = 'deviceId=' + deviceId;
			that.jsonApiService.http("track/follow.html", reqdata).subscribe(result => {
				if(!result.success) {
					that.jsonApiService.message(result.message);
					that.closeInfo();
					return;
					//如果请求不成功,不执行
				}
				let len = that.TrackLineArr.length;
				let toMap = toMapPoint(result.data);
				that.TrackLineArr.push(toMap);
				if(len >= 180) {//10秒一次 30分钟=180个数据
					that.TrackLineArr.shift();
				}
				that.lineStyle.infoUrl = config.BaseURL;
				drawTrackLine(that.TrackLineArr, that.mp, that.lineStyle);
				that.getWeightUnit(deviceId).then((carInfoData)=>{
					that.createContent(carInfoData, true).then((content) => {
						$('.closeInfo').click(function() {
							that.closeInfo();
						})
						$('.stopRoute').click(function() {
							that.stopPolylinetimer(deviceId);
						})
						$('.toCarTrack').click(function() {
							that.toCarTrackHtml();
						})
						$('.toDataload').click(function() {
							that.toloadDataHtml();
						})
						that.mapInfoWindow.disableCloseOnClick();
					});
				})
			})
		}, that.frequency)
	}

	//轨迹暂停,继续事件,
	stopPolylinetimer(deviceId) {
		if(this.isStopStatus) {
			$('.stopRoute').text('暂停');
			this.isStopStatus = false;
			this.runTimer(deviceId);
		} else {
			$('.stopRoute').text('继续');
			this.isStopStatus = true;
			clearInterval(this.polylinetimer);
		}
	}
	toCarTrackHtml(){
		let device_id=$('.device_id').text();
		let car_number=$('.car_number').text();
		var ndate = new Date();
		let endTime=common.getTimeMmss(ndate)
		ndate.setDate(ndate.getDate() - 1);
		let startTime=common.getTimeMmss(ndate);
		this.router.navigate(['/car/car-path'],{ queryParams: {
			carNumber:car_number,
			deviceId:device_id,
			startTime:startTime,
			endTime:endTime,
			type:'detail'
		}});
		setTimeout(function(){
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display','none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display','block');
		},300)
	}
	toloadDataHtml(){
	    console.log('===============11111111111============')
		let device_id=$('.device_id').text();
		let car_number=$('.car_number').text();
		var ndate = new Date();
		let endTime=common.getTimeMmss(ndate)
		ndate.setDate(ndate.getDate() - 1);
		let startTime=common.getTimeMmss(ndate);
		this.router.navigate(['/data-management/load-data'],{ queryParams: {
			carNumber:car_number,
			deviceId:device_id,
			startDate:startTime,
			endDate:endTime,
		}});
		setTimeout(function(){
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display','none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display','block');
		},300)
	}

}